﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HttpProxy
{
    class Program
    {
        static void Main(string[] args)
        {
            const int port = 8000;
            //定义端口号
            TcpListener tcplistener = new TcpListener(IPAddress.Parse("127.0.0.1"),port);
            Console.WriteLine("侦听端口号： " + port.ToString());
            tcplistener.Start();
            //侦听端口号
//            while (true)
            {
                TcpClient client = tcplistener.AcceptTcpClient();
                SslStream sslStream = new SslStream(client.GetStream(),true, ValidateServerCertificate,null);
                // The server name must match the name on the server certificate.

                X509Store store = new X509Store(StoreName.Root);
                store.Open(OpenFlags.ReadWrite);

                //// 检索证书 
                X509Certificate serverCertificate = new X509Certificate2(Environment.CurrentDirectory + @"\" + "ProxyServer.pfx", "yytcdj");
                
                try
                {
                    sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls12, true);
                }
                catch (AuthenticationException e)
                {
                    Console.WriteLine("Exception: {0}", e.Message);
                    if (e.InnerException != null)
                    {
                        Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                    }
                    Console.WriteLine("Authentication failed - closing the connection.");
                    client.Close();
                    return;
                }

                //并获取传送和接收数据的Scoket实例
                Proxy proxy = new Proxy(sslStream);
                //Proxy类实例化
                Thread thread = new Thread(proxy.Run);
                //创建线程
                thread.Start();
                //启动线程
            }
            Console.ReadKey();
        }

        public static bool ValidateServerCertificate(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    }
}